package fallon;

import com.adxon.cookie.Station;
import com.adxon.data.Item;
import com.adxon.servlet.ServletBase;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class UploadServlet extends ServletBase{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException{
		setAttributes(req,"Upload");
		forward("upload.jsp",req,resp);
	}
	public void doPost(HttpServletRequest req,HttpServletResponse resp)
			throws IOException, ServletException{
		resp.setContentType("text/plain");
		try{
			FileItemIterator t=new ServletFileUpload().getItemIterator(req);
			while(t.hasNext()){
				FileItemStream f=t.next();
				if (!f.isFormField()){
					Collection c=new Collection();
					Item u=Station.getCurrentUser(req);
					if(u!=null){
						Collection.refresh(u.getId());
						c.setOwner(u);
						c.setRate(60);
						c.setBits(f.openStream());
						c.setContentType(f.getContentType());
						c.setMaxSize("1536");
						c.setRatio("3:4");
						c.commit();
						resp.getWriter().println("Ok");
						return;
					}
				}
			}
		}catch(Exception ex){
			throw new ServletException(ex);
		}
		resp.getWriter().println("Bad");
	}
}